package com.netease.research.service.impl;

import com.netease.research.service.IFileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service("iFileService")
public class FileServiceImpl implements IFileService {

    @Override
    public String upload(MultipartFile file, String path){
        String fileName = file.getOriginalFilename();
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".")+1);
        String uploadFileName = UUID.randomUUID()+"."+fileExtensionName;

        File fileDir = new File(path);
        if(!fileDir.exists()){
            fileDir.mkdirs();
        }
        fileDir.setWritable(true);
        File targetFile = new File(path, uploadFileName);

        try{
            file.transferTo(targetFile);
            targetFile.setReadable(true, false);
            targetFile.setWritable(true,false);
            targetFile.setExecutable(true,false);
        }catch (IOException e){
            return null;
        }
        return targetFile.getName();
    }
}
